package org.jflame.commons.convert;

import org.jflame.commons.util.DateHelper;
import org.jflame.commons.util.StringHelper;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.commons.lang3.tuple.ImmutablePair;

/**
 * 新时间类型格式化为字符串.如:LocalDate,LocalDateTime,LocalTime
 * 
 * @author charles.zhang
 */
public class TemporalToStringConverter extends ObjectToStringConverter<TemporalAccessor> implements ConvertibleType {

    private DateTimeFormatter formatter;

    public TemporalToStringConverter() {
    }

    public TemporalToStringConverter(String pattern) {
        StringHelper.requireNonEmpty(pattern, "'pattern' must not be empty");
        this.formatter = DateTimeFormatter.ofPattern(pattern);
    }

    public TemporalToStringConverter(DateTimeFormatter formatter) {
        this.formatter = formatter;
    }

    @Override
    public String convert(TemporalAccessor source) {
        if (source == null) {
            return null;
        }
        if (formatter == null) {
            if (source instanceof LocalDate) {
                /*if (tzContext != null && tzContext.isDiffZone()) {
                    return DateTimeFormatter.ISO_LOCAL_DATE
                            .format(DateHelper.changeZone(((LocalDate) source), getZoneId()));
                }*/
                return DateTimeFormatter.ISO_LOCAL_DATE.format(source);
            } else if (source instanceof LocalDateTime) {
                return DateHelper.FORMATTER_YYYY_MM_DD_HH_mm_ss.format(source);
            } else if (source instanceof ZonedDateTime) {
                return DateHelper.FORMATTER_YYYY_MM_DD_HH_mm_ss.format(source);
            } else if (source instanceof LocalTime) {
                return DateTimeFormatter.ISO_LOCAL_TIME.format(source);
            } else {
                return source.toString();
            }
        }
        return formatter.format(source);
    }

    @Override
    public Set<ImmutablePair<Class<?>,Class<?>>> getConvertibleTypes() {
        Set<ImmutablePair<Class<?>,Class<?>>> convertibleTypes = new LinkedHashSet<>();
        convertibleTypes.add(ImmutablePair.of(LocalDateTime.class, String.class));
        convertibleTypes.add(ImmutablePair.of(LocalDate.class, String.class));
        convertibleTypes.add(ImmutablePair.of(LocalTime.class, String.class));
        return convertibleTypes;
    }

}
